package org.example;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Ticket {
    private int count = 3; // 售卖总票数
    private final Lock lock = new ReentrantLock(); // 互斥锁1

    public void sale() { // 售票业务
        this.lock.lock(); // 资源锁定
        try {
            if (this.count > 0) { // 有剩余票数
                TimeUnit.SECONDS.sleep(1); // 模拟操作延迟
                System.out.println("【" + Thread.currentThread().getName() + "】卖票，剩余票数：" + this.count--);
            } else {
                System.err.println("【" + Thread.currentThread().getName() + "】票已卖完了，明天再来！");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("Thread was interrupted: " + e.getMessage());
        } finally {
            this.lock.unlock(); // 解除锁定
        }
    }
}

